// pages/mine/profile/profile.js
const app = getApp()
const i18n = require('../../../utils/i18n/index')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        cdnUrl: app.globalData.cdnUrl,
        userInfo: {
            name: '',
            phone: '',
            company: '',
            position: '',
            avatar_url: '',
            bl_image:''
        },
        locale: 'zh_CN',
        t: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setI18nData()
        this.loadUserInfo()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.setNavigationBarTitle({
            title: i18n.t('mine.menu.settings')
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    setI18nData() {
        this.setData({
            locale: i18n.getLocale(),
            t: {
                title: i18n.t('mine.profile.title'),
                name: i18n.t('mine.profile.name'),
                phone: i18n.t('mine.profile.phone'),
                company: i18n.t('mine.profile.company'),
                position: i18n.t('mine.profile.position'),
                save: i18n.t('mine.profile.save'),
                namePlaceholder: i18n.t('mine.profile.namePlaceholder'),
                phonePlaceholder: i18n.t('mine.profile.phonePlaceholder'),
                companyPlaceholder: i18n.t('mine.profile.companyPlaceholder'),
                positionPlaceholder: i18n.t('mine.profile.positionPlaceholder'),
                saveSuccess: i18n.t('mine.profile.saveSuccess'),
                blicence: i18n.t('mine.profile.blicence'),
                saveFail: i18n.t('mine.profile.saveFail'),
                incomplete: i18n.t('mine.profile.incomplete'),
                uploadImage: i18n.t('supply.publish.uploadImage'),
                maxImages: i18n.t('supply.publish.maxImages'),
                uploading: i18n.t('supply.publish.uploading'),
                uploadFailed: i18n.t('supply.publish.uploadFailed'),
            }
        })
    },

    onLanguageChange() {
        this.setI18nData()
    },

    // 加载用户信息
    loadUserInfo() {
        wx.request({
            url: app.globalData.baseUrl + 'api/user-info',
            header: {
                'Authorization': `Bearer ${app.globalData.token}`
            },
            success: res => {
                if (res.data.code === 0) {
                    this.setData({
                        userInfo: res.data.data.user || {}
                    })
                }
            }
        })
    },

    // 选择头像
    onChooseAvatar(e) {
        const { avatarUrl } = e.detail
        
        wx.showLoading({ title: this.data.t.uploading })
        return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: app.globalData.baseUrl + 'api/upload',
            filePath: avatarUrl,
            name: 'file',
            header: {
            'Authorization': `Bearer ${app.globalData.token}`
            },
            success: res => {
            const data = JSON.parse(res.data)
            if (data.code === 0) {
                this.setData({
                    'userInfo.avatar_url': data.url
                })
                wx.hideLoading()
                resolve()
            } else {
                wx.showToast({
                title: this.data.t.uploadFailed,
                icon: 'none'
                })
                reject()
            }
            },
            fail: () => {
            wx.showToast({
                title: this.data.t.uploadFailed,
                icon: 'none'
            })
            reject()
            }
        })
        })

    },

    // 输入处理
    onInput(e) {
        const { field } = e.currentTarget.dataset
        this.setData({
            [`userInfo.${field}`]: e.detail.value
        })
    },

     // 选择图片
  chooseImage() {
    const count = 9
    wx.chooseMedia({
      count,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tasks = res.tempFiles.map(file => this.uploadImage(file))
        Promise.all(tasks).then(() => {
          wx.hideLoading()
        })
      }
    })
  },
// 上传图片
uploadImage(file) {
    wx.showLoading({ title: this.data.t.uploading })
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: app.globalData.baseUrl + 'api/upload',
        filePath: file.tempFilePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${app.globalData.token}`
        },
        success: res => {
          const data = JSON.parse(res.data)
          if (data.code === 0) {
            this.setData({
              'userInfo.bl_image': data.url
            })
            resolve()
          } else {
            wx.showToast({
              title: this.data.t.uploadFailed,
              icon: 'none'
            })
            reject()
          }
        },
        fail: () => {
          wx.showToast({
            title: this.data.t.uploadFailed,
            icon: 'none'
          })
          reject()
        }
      })
    })
  },
    // 保存资料
    onSave() {
        const { userInfo } = this.data
        console.log("userInfo", userInfo)
        // 表单验证
        if (!userInfo.name || !userInfo.phone || !userInfo.company || !userInfo.position) {
            wx.showToast({
                title: this.data.t.incomplete,
                icon: 'none'
            })
            return
        }

        wx.showLoading({ title: i18n.t('common.loading') })

        wx.request({
            url: app.globalData.baseUrl + 'api/user-profile',
            method: 'POST',
            header: {
                'Authorization': `Bearer ${app.globalData.token}`
            },
            data: userInfo,
            success: res => {
                if (res.data.code === 0) {
                    wx.showToast({
                        title: this.data.t.saveSuccess,
                        icon: 'success'
                    })
                    setTimeout(() => {
                        wx.navigateBack()
                    }, 1500)
                } else {
                    wx.showToast({
                        title: this.data.t.saveFail,
                        icon: 'none'
                    })
                }
            },
            fail: () => {
                wx.showToast({
                    title: this.data.t.saveFail,
                    icon: 'none'
                })
            },
            complete: () => {
                wx.hideLoading()
            }
        })
    }
})